#pragma once
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <cerrno>
#include <cstring>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "nocopy.hpp"
#include "Log.hpp"
#include "comm.hpp"
#include "Inet_Addr.hpp"

// const static std::string default_ip = "0.0.0.0";
const static uint16_t default_port = 8888;
const static int default_soctfd = -1;
const static int default_size = 1024;

class UdpServer : public nocopy
{
public:
    UdpServer(uint16_t port = default_port)
        : _port(port), _sockfd(default_soctfd)
    {
    }
    void Init()
    {
        // 1.创建socket
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0); // 创建的是udp
        if (_sockfd < 0)
        {
            lg.LogMessage(Fatal, "socket error: %d : %s\n", errno, strerror(errno));
            exit(Socket_Err);
        }

        // 2.绑定，指定网络信息
        struct sockaddr_in local;
        bzero(&local, sizeof(local)); // 相当于memset
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;
        // local.sin_addr.s_addr = inet_addr(_ip.c_str());
        // 1.将字符串风格的ip地址转换为4字节的ip
        // 2.并且转换为网络字节序

        // 结构体设置完成了，设置到内核中了吗？没有
        int n = ::bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
        if (n != 0)
        {
            lg.LogMessage(Fatal, "bind error, %d : %s\n", errno, strerror(errno));
            exit(Bind_Err);
        }
    }
    void Start()
    {
        // 服务器永远不退出
        char buffer[default_size];
        for (;;)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int n = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, &len);
            if (n > 0)
            {
                buffer[n] = 0;
                Inet_Addr addr(peer);
                std::cout << "[" << addr.PrintDebug() << "]# " << buffer << std::endl;
                // 服务端收到客户端消息后，将该消息又发送回去
                sendto(_sockfd, buffer, strlen(buffer), 0, (struct sockaddr *)&peer, len);
            }
        }
    }
    ~UdpServer() {}

private:
    // std::string _ip;
    uint16_t _port;
    int _sockfd;
};